<?php

    // +----------------------------------------------------------------------
    // | 订单管理
    // +----------------------------------------------------------------------
    // | Copyright (c) 2015-2024 http://www.yicmf.com, All rights reserved.
    // +----------------------------------------------------------------------
    // | Author: 微尘 <yicmf@qq.com>
    // +----------------------------------------------------------------------

    namespace app\controller\store\admin;

    use yicmf\builder\View;
    use app\model\store\Order as OrderModel;
    use app\event\store\Order as OrderEvent;
    use yicmf\builder\Edit;
    use yicmf\builder\Table;
    use think\facade\Url;
    use app\event\ucenter\User as UserEvent;

    class Order extends Common
    {
        protected function initialize()
        {
            parent::initialize();
            $this->model = new OrderModel();
        }

        public function _filter()
        {
            if (!$this->request->param('status')) {
                $map[] = ['status', '>', -1];
            }
            $map[] = ['delete_status', 'in', '0,1'];
            return $map;
        }

        /**
         * 订单列表
         * @return mixed|string
         * @author  : 微尘 <yicmf@qq.com>
         */
        public function index()
        {
            // 显示页面
            $statusOptions = [
                [
                    'id' => 0,
                    'value' => '已取消'
                ],
                [
                    'id' => 1,
                    'value' => '待支付'
                ],
                [
                    'id' => 2,
                    'value' => '待发货'
                ],
                [
                    'id' => 3,
                    'value' => '待确认'
                ],
                [
                    'id' => 5,
                    'value' => '已完成'
                ]
            ];
            $where = $this->_filter();
            // 显示页面
            $builder = new Table();
            $builder->model(OrderModel::class)
                ->where($where)
                ->order('id DESC')
//                ->suggest('高等级可以对低等级用户进行操作或者授权')
//            ->searchUser('下单用户')
                ->searchSelect('status', '订单状态', $statusOptions)
                ->searchTextLike('sn', '订单号')
//            ->buttonUpdate('update?type=0')
                ->keyId()
                ->keyText('sn', '订单号')
                ->keyText('name', '订单名称')
                ->keyText('address_info_text', '地址', false, 200)
                ->keyText('amount', '订单金额')
//            ->keyText('remark', '备注')
                ->keyUser('user_id', '下单用户')
                ->keyClosure('邀请人', function ($data) {
                    $pid = UserModel::where('id', $data['user_id'])->value('pid');
                    if ($pid) {
                        $user = UserModel::where('id', $pid)->find();
                        if ($user) {
                            return $user['nickname'] . '(' . $user['id'] . ')';
                        }
                    }
                    return '-';
                })
                ->keyTime('pay_time', '支付时间')
//            ->keyTime('cancel_time','取消时间')
//				->keyText('description', '描述')
                ->keyCreateTime('下单时间')
                ->keyStatus(['已取消', '待支付', '待发货', '待确认', '已完成', '已完成'])
//            ->quickUpdate(['title','description'])
                ->actionView('view?id={$id}', '详情', function ($data) {
                    return true;
                })
                ->actionUpdate('pay?id={$id}', '支付', [1])
                ->actionUpdate('send?id={$id}', '发货', [2]);
//            ->actionDelete();
//            ->actionForbid('forbid?id={$id}', '禁用', function ($data) {
//                return 1 == $data['status'] && 1 < $data['id'];
//            });
            return $builder->fetch();
        }

        /**
         * 取消订单
         * @throws \Exception
         * @author  : 微尘 <yicmf@qq.com>
         * @datetime: 2019/4/28 14:00
         */
        public function cancel()
        {
            $order = new OrderEvent();
            $result = $order->saleCancel($this->request->param(), $this->user);
            if (0 == $result['code']) {
                $this->_returnSuccess( '取消成功');
            } else {
                $this->_returnError( '失败，失败信息：' . $result['message']);
            }
        }

        public function del()
        {
            $order = $this->model->find($this->request->get('id'));
            if (1 == $order['delete_status']) {
                $order['delete_status'] = 3;
            } else {
                $order['delete_status'] = 2;
            }
            if ($order->save()) {
                $this->_returnSuccess( '删除成功');
            } else {
                $this->_returnError( '失败，失败信息：');
            }
        }

        public function view()
        {
			$order = OrderModel::where('id',$this->request->param('id',41))->find();
			if (!$order) {
				$this->_returnError( '信息不存在');
			}

			$this->assign('order',$order);
			return $this->fetch();
        }

        /**
         * 编辑订单价格备注
         * @return string|void
         * @throws \Exception
         * @author  : 微尘 <yicmf@qq.com>
         */
        public function update()
        {
            if ($this->request->isPost()) {
                $validate = $this->validate($this->request->post(), 'Order');
                if (true === $validate) {
                    $event = new OrderEvent();
                    $result = $event->updatePrice($this->request->post(), $this->user);
                    if (0 == $result['code']) {
                        $this->_returnSuccess( $result['message'], true);
                    } else {
                        $this->_returnError( $result['message']);
                    }
                } else {
                    $this->_returnError( $validate);
                }
            } else {
                $id = $this->request->get($this->model->getPk());
                // 判断是否为编辑模式
                $isEdit = $id ? true : false;
                $builder = new Edit();
                if ($isEdit) {
                    $data = $this->model->get($id);
                } else {
                    $this->_returnError( '订单不存在');
                }
                $builder->title('编辑订单')
                    ->keyLabel('course_titles', '商品名称')
                    ->keyLabel('user.nickname', '用户昵称')
                    ->keyDecimal('real_amount', '实际付款', '用户真实需要支付的金额')
                    ->keyTextArea('remark', '备注', '')
                    ->data($data)
                    ->buttonSubmit('', '保 存')
                    ->buttonClose();
                return $builder->fetch();
            }
        }

        public function statistics()
        {
            $result = $this->model
                ->field('DATE_FORMAT(create_time,"%Y%m") days,count(id)  num')->whereTime('create_time', date('Y-m-01') . ' -6 month')->group('days')->select();
            $result2 = $this->model->where('status', 5)
                ->field('DATE_FORMAT(payment_time,"%Y%m") days,count(id)  num')->whereTime('payment_time', date('Y-m-01') . ' -6 month')->group('days')->select();
            //            $chart = new Chart();
            $data = [];
            $data['tooltip'] = ['trigger' => 'axis'];
            $data['legend'] = ['data' => ['下单量', '成交量']];
            $data['toolbox'] = ['show' => true, ''];
            $x = [];
            $series = [];
            for ($i = 6; $i >= 0; $i--) {
                $day = date('Ym', strtotime(date('Y-m-01') . ' -' . $i . '  month'));
                $num = 0;
                $x[] = $day;
                foreach ($result as $item) {
                    if ($item['days'] == $day) {
                        $num = $item['num'];
                        break;
                    }
                }
                $series[] = $num;
                $num = 0;
                foreach ($result2 as $item) {
                    if ($item['days'] == $day) {
                        $num = $item['num'];
                        break;
                    }
                }
                $series2[] = $num;
            }
            $series2 = [];
            $data['xAxis'] = ['type' => 'category', 'data' => $x];
            $data['yAxis'] = ['type' => 'value'];
            $data['series'] = [
                ['name' => '下单量', 'type' => 'line', 'data' => $series],
                ['name' => '成交量', 'type' => 'line', 'data' => $series2],
            ];
            return json($data);
        }


		/**
		 * 周期统计
		 */
		public function cycle()
		{
			// 显示页面
			$statusOptions = [
				[
					'id' => 0,
					'value' => '本周',
				],
				[
					'id' => 1,
					'value' => '本月',
				],
				[
					'id' => 2,
					'value' => '上月',
				],
				[
					'id' => 3,
					'value' => '当年',
				],
				[
					'id' => 5,
					'value' => '上年',
				],
			];


			$field = $this->request->param('field/a');
			$map = [];
			$map[] = ['status', '>', -2];
			if (isset($field['status'])) {
				if (0 == $field['status']) {
					$map[] = ['create_time', 'between time', [time_format('this week 00:00:00'), time_format('next week 00:00:00 -1second')]];
					$cycle = '本周';
				} elseif (1 == $field['status']) {
					$cycle = '本月';
					$map[] = ['create_time', 'between time', [time_format('first Day of this month 00:00:00'), time_format('first Day of next month 00:00:00 -1second')]];
				} elseif (2 == $field['status']) {
					$cycle = '上月';
					$map[] = ['create_time', 'between time', [time_format('first Day of last month 00:00:00'), time_format('first Day of this month 00:00:00 -1second')]];
				} elseif (3 == $field['status']) {
					$cycle = '当年';
					$map[] = ['create_time', 'between time', [time_format('this year 1/1'), time_format('next year 1/1 -1second')]];
				} elseif (5 == $field['status']) {
					$cycle = '上年';
					$map[] = ['create_time', 'between time', [time_format('last year 1/1'), time_format('this year 1/1 -1second')]];
				}

			} else {
				$cycle = '全部';
			}


			$data[] = [
				'id' => 1,
				'add' => OrderModel::where($map)->where('status', '>=', 0)->count(),
				'pay' => OrderModel::where($map)->where('status', '>=', 2)->count(),
				'send' => OrderModel::where($map)->where('status', '>=', 3)->count(),
				'finish' => OrderModel::where($map)->where('status', '>=', 5)->count(),
				'cancel' => OrderModel::where($map)->where('status', '=', 0)->count(),
				'cycle' => $cycle
			];
			// 显示页面
			$builder = new Table();
			$builder->searchSelect('status', '周期', $statusOptions)
				->keyId()
				->keyText('cycle', '周期')
				->keyText('add', '新增')
				->keyText('pay', '支付')
				->keyText('send', '发货')
				->keyText('finish', '完成')
				->keyText('cancel', '取消')
				->data($data, false);
			return $builder->fetch();
		}


		/**
         * 订单列表
         * @return mixed|string
         * @author  : 微尘 <yicmf@qq.com>
         * @datetime: 2019/4/27 21:09
         */
        public function home()
        {
            // 显示页面
            // 显示页面
            $builder = new Table();
            $builder->model(OrderModel::class)
                ->where($this->_filter())
                ->order('id DESC')
                ->keyId()
                ->keyText('order_sn', '订单号')
				->keyClosure('商品信息', function($data) {
					$goods = $data->goods()->select();
					$html = '';
					foreach ($goods as $good) {
						$html .=$good->title . '*' . $good['quantity'];
					}
					return $html;
				}, 180)
                ->keyText('quantity', '[购买数量]')
                ->keyText('remark', '[订单备注]')
                ->keyDecimal('real_amount', '支付金额')
                ->keyCreateTime()
                ->keyIp('ip', '下单IP')
                ->keyStatus([
                    -1 => '已经关闭',
                    0 => '已取消',
                    1 => '未付款',
                    2 => '已付款',
                    3 => '已发货',
                    5 => '已完结'
                ]);
            return $builder->fetch();
        }

    }
